/**
 * this class administrates the Properties File
 */

package co.edu.unal.satacredito.database.connection;

import co.edu.unal.satacredito.database.entity.Establishment;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Miguel Alexander Diaz 257835
 */

public class EstablishmentDatastoreFactory {
    
    private static final String SATACREDITO_PATH = "SATACREDITO_PATH";    
    private static final String FILE_PATH = "config/connection";    
    private static final String FILE_NAME = "establishment";
    
    private static final String HOST = "HOST";
    private static final String PORT = "PORT";
    
    private static final String DB = "satacredito";
    
    private EstablishmentDatastoreFactory() {
    }
    
    public static synchronized Datastore createDatastore() throws UnknownHostException, MongoException {
        PropertiesVO pvo = null;
        try {
            pvo = localProperties();
            Mongo mongo = new Mongo(pvo.getHost(), pvo.getPort());
            Morphia morphia = new Morphia();
            morphia.map(Establishment.class);
            return morphia.createDatastore(mongo, DB);
        } catch (IOException ioe) {
            Logger.getLogger(AdministratorDatastoreFactory.class.getName()).log(Level.SEVERE, null, ioe);
            return null;
        }
    }

    private static PropertiesVO localProperties() throws IOException {
        Properties properties = new Properties();
        properties.load(new FileInputStream(System.getenv(SATACREDITO_PATH) + "/" +
                                            FILE_PATH + "/" + FILE_NAME + ".properties"));
        PropertiesVO pvo = PropertiesVO.getInstance();
        pvo.setHost(properties.getProperty(HOST));
        pvo.setPort(new Integer(properties.getProperty(PORT)));
        return pvo;
    }
    
    private static final class PropertiesVO {
        private static PropertiesVO instance = null;
        private String host;
        private Integer port;
        private PropertiesVO() {
        }
        public static synchronized PropertiesVO getInstance() {
            if (instance == null) {
                instance = new PropertiesVO();
            }
            return instance;
        }
        public String getHost() {
            return host;
        }
        public void setHost(String host) {
            this.host = host;
        }
        public Integer getPort() {
            return port;
        }
        public void setPort(Integer port) {
            this.port = port;
        }
    }
}